package com.itheima.web.controller.system;

import com.itheima.common.utils.UtilFuns;
import com.itheima.doamin.system.Dept;
import com.itheima.service.system.DeptService;
import com.itheima.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@RequestMapping("/system/dept")
@Controller
public class DeptController extends BaseController{
    /**
     *fenye 查询所有
     */
    @Autowired
    DeptService deptService;
    @RequestMapping("list")
    public String list(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "3") int size){
        request.setAttribute("page",deptService.findAll(page,size,super.getCurrentUser().getCompanyId()));
        return "system/dept/dept-list";
    }

    //添加
    @RequestMapping("toAdd")
    public String toAdd(){
        List<Dept> deptList = deptService.findAll(super.getCurrentUser().getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-add";
    }

    //更新
    @RequestMapping("toUpdate")
    public String toUpdate(String id){
        Dept dept = deptService.findById(id);
        request.setAttribute("dept",dept);
        List<Dept> deptList = deptService.findAll(super.getCurrentUser().getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-update";
    }

    /**
     * 进行更新或则添加操作
     * @param dept
     * @return
     */
    @RequestMapping("edit")
    public String edit(Dept dept){
        if (UtilFuns.isEmpty(dept.getId())){
            //为空则保存
            dept.setCompanyId(super.getCurrentUser().getCompanyId());
            dept.setCompanyName(super.getCurrentUser().getCompanyName());
            deptService.save(dept);
        }else {
            deptService.update(dept);
        }
        return "redirect:/system/dept/list";
    }

    //删除
    @RequestMapping("delete")
    public String delete(String id){
        deptService.delete(id);
        return "redirect:/system/dept/list";
    }
}
